package com.sihai.ehr.jdbc;

import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * author: wxn
 * since: 13-8-7 下午9:58
 */
public class JDBCHelper {
    private static Connection connection;

    public static Connection connection(){
        if(connection != null){
            return connection;
        }

        String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";  //加载JDBC驱动
        //String dbURL = "jdbc:sqlserver://localhost:1433; DatabaseName=bsv5";  //连接服务器和数据库
        //String userName = "sa";  //默认用户名
        //String userPwd = "sa";  //密码
        try {
            Properties properties = PropertiesLoaderUtils.loadAllProperties("jdbc.properties");
            String dbURL = properties.getProperty("ms_db_url", "jdbc:sqlserver://localhost:1433; DatabaseName=bsv5");
            String userName = properties.getProperty("ms_user_name", "sa");  //默认用户名
            String userPwd = properties.getProperty("ms_user_password", "sa123");  //密码

            Class.forName(driverName);
            connection = DriverManager.getConnection(dbURL, userName, userPwd);
            System.out.println("Connection Successful!");  //如果连接成功 控制台输出Connection Successful!
            return connection;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void close(Connection connection){
        try {
            if(connection != null && !connection.isClosed()){
                connection.close();
            }
            connection = null;
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Connection con = connection();
        if(con != null){
            close(con);
        }
    }
}
